﻿package src.com.online.rpg
{
	import flash.display.MovieClip;
	import flash.events.Event;
	
	/*
		 AnimatedGameObject
		 ------------------
		 Time-based controller for MovieClip-based animated objects.
		 Each from of the MovieClip contains a different animation (run up, run down, idle, etc.)
	*/ 
	public class AnimatedGameObject extends GameObject
	{
		protected var _movieClip:MovieClip;
		
		private var _frameAccumulator:Number = 0;	// animation timer
		private var _frameTime:Number = 1.0 / 30;	// animation frame time (30fps)

		public function AnimatedGameObject(movieClip:MovieClip) 
		{
			super(movieClip);

			_movieClip = movieClip;
			
			_movieClip.stop();
			if (animation) animation.stop();
		}
		
		// Different animations are on separate frames inside the movieclip, with an instance name of "animation"
		public function get animation():MovieClip	{ return _movieClip.animation; }

		// Update animation state
		public override function update(dt:Number):void
		{			
			if (animation)
			{
				_frameAccumulator += dt;
				
				// if we've accumulated a new frame,
				while (_frameAccumulator >= _frameTime)
				{
					//  jump to next frame
					if (animation.currentFrame == animation.totalFrames)
					{
						// loop the animation
						dispatchEvent(new Event(GameEvent.ANIMATION_COMPLETE));
						animation.gotoAndStop(1);
					}
					else
					{
						animation.nextFrame();
					}
					
					_frameAccumulator -= _frameTime;
				}
			}
		}
		
		// This will check inside the animation to see if a flag was set on the timeline.
		// Useful for frame-specific events and properties
		// Note that if your timestep (dt) is too large, you may jump over these flags, missing them!
		// A fix could be to throw an event when a flag is seen, as opposed to relying on polling
		public function checkAnimationFlag(flag:String):Boolean
		{
			return animation && animation[flag];
		}
		
		// Change the current animation
		public function changeAnimation(animationName:String, goToFirstFrame:Boolean = true):void
		{
			var frame:uint = 1;
			if (goToFirstFrame)
			{
				_frameAccumulator = 0;
			}
			else if (animation)
			{
				frame = animation.currentFrame;
			}
						
			_movieClip.gotoAndStop(animationName);
			
			if (animation) animation.gotoAndStop(frame);
		}
		
	}

}